package com.hr.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.google.gson.Gson;
import com.hr.mapper.TagMapper;
import com.hr.pojo.Tag;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


import java.util.*;

@Service
public class TagServiceimpl implements TagServiceMapper{
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    @Cacheable(value = "tagCache")
    public List getTagList(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ge("id",id);
        List<Tag> tagList = tagMapper.selectList(queryWrapper);
        //准备连接池
        JedisPoolConfig jedis = new JedisPoolConfig();
        //设置最大连接数  最大空闲数
        jedis.setMaxTotal(1000);//最大连接数
        jedis.setMaxIdle(60);//最大空闲数
        //从池中获取连接
        JedisPool jedisPool = new JedisPool(jedis,"127.0.0.1", 6379);
        Jedis resource = jedisPool.getResource();
        //准备map集合
        Map<Integer,Object> map = new HashMap<>();
        //遍历taglist集合数据
        //将数据封装到map
        System.out.println("======================111======================");
        /*Jedis jedis = new Jedis("127.0.0.1", 6379);*/
        Gson gson=new Gson();
        for (int i = 0; i < tagList.stream().count(); i++) {
            System.out.println(tagList.get(i));//tagList.get(i) 分离两个数据
            map.put(i,tagList.get(i));
            //遍历元素存到集合
            String jsonStr=gson.toJson(tagList.get(i));
            System.out.println(jsonStr);
            resource.lset("tags", i, jsonStr);
        }
        //将map存储到redis
        //准备jedis
        /*map.put(1,"200");*/
        System.out.println("======================111======================");
        //连接池取得k
        Map<String, String> tags = resource.hgetAll("tags");
        //转换为list集合
        Collection<String> values = tags.values();//取得tags的value
        System.out.println(values);
        List<String> tagsList = new ArrayList(values);
        //关闭连接池
        resource.close();
        //将对象转换为json格式字符串
        return tagsList;
    }
}
